import time

import requests
import pymongo

client = pymongo.MongoClient()
db = client.get_database('bibi')
db.drop_collection('bibi_data')
collection = db.get_collection('bibi_data')

headers = {
    "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"
}

for page in range(1,198):
    res = requests.get(
        f'https://api.bilibili.com/pgc/season/index/result?st=1&order=3&season_version=-1&spoken_language_type=-1&area=-1&is_finish=-1&copyright=-1&season_status=-1&season_month=-1&year=-1&style_id=-1&sort=0&page={page}&season_type=1&pagesize=20&type=1',
        headers=headers)
    print(f'正在打印{page}页')
    items = res.json()['data']['list']
    total = res.json()['data']['total']
    for item in items:
        title = item['title']
        index_show = item['index_show']
        img_url = item['cover']
        rr = requests.get(img_url)
        file_name = img_url.split('/')[-1]
        collection.insert_one({
            'title': title,
            'index_show': index_show,
            'img_url': img_url
        })
        print(f'正在爬取{file_name}图片')
        with open(f'./images2/{file_name}', 'wb') as f:
            f.write(rr.content)
        time.sleep(1)
    break

client.close()